//
// Created by HP on 2025/11/26.
//

#include "StationTrain.h"
#include <iostream>

StationTrain::StationTrain() : Model("station_trains") {
    setTableDefault("station_id", "VARCHAR(50) NOT NULL");
    setTableDefault("train_id", "VARCHAR(50) NOT NULL");
    setTableDefault("station_order", "INT NOT NULL");
    setTableDefault("arrival_time", "VARCHAR(50)");
    setTableDefault("departure_time", "VARCHAR(50)");
    setTableDefault("stop_duration", "VARCHAR(50)");
    setTableDefault("createdAt", "DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP");
    
    // 创建外键约束（可选，取决于数据库配置）
    // addForeignKey("station_id", "stations", "id");
    // addForeignKey("train_id", "trains", "id");
}

void StationTrain::bind(const std::string& key, const std::string& value) {
    if (!TableCols.count(key)) {
        std::cerr << "Error: Invalid key for station_train bind" << std::endl;
        return;
    }
    
    std::string selectSql = "SELECT * FROM " + TableName + " WHERE " + key + " = '" + Model::escapeSqlLiteral(value) + "';";
    std::vector<std::map<std::string, std::string>> result = DBConnector::getInstance()->query(selectSql);

    if (result.empty()) {
        std::cerr << "bind failed: SQL execution error or no result. SQL: " << selectSql << std::endl;
        return;
    }

    std::cout << "bind success. Table: " << TableName << std::endl;

    // 由于可能有多条记录（同一station_id或train_id可能有多条记录），这里只取第一条
    if (result.size() > 1) {
        std::cout << "Warning: Multiple station_train records found with the same " << key << ", using the first one." << std::endl;
    }
    
    this->id = result[0]["id"];
    this->station_id = result[0]["station_id"];
    this->train_id = result[0]["train_id"];
    this->station_order = result[0]["station_order"];
    this->arrival_time = result[0]["arrival_time"];
    this->departure_time = result[0]["departure_time"];
    this->stop_duration = result[0]["stop_duration"];
    this->createdAt = result[0]["createdAt"];
    this->isBind = true;
}

bool StationTrain::save() {
    std::string insertSql = "INSERT INTO " + TableName + " (station_id, train_id, station_order, arrival_time, departure_time, stop_duration) VALUES ('" 
                          + Model::escapeSqlLiteral(station_id) + "', '" 
                          + Model::escapeSqlLiteral(train_id) + "', '" 
                          + Model::escapeSqlLiteral(station_order) + "', '" 
                          + Model::escapeSqlLiteral(arrival_time) + "', '" 
                          + Model::escapeSqlLiteral(departure_time) + "', '" 
                          + Model::escapeSqlLiteral(stop_duration) + "');";
    
    int executeCode = DBConnector::getInstance()->execute(insertSql);
    if (executeCode == -1) {
        std::cerr << "save station_train failed: SQL execution error. SQL: " << insertSql << std::endl;
        std::cerr << "Database error: " << DBConnector::getInstance()->getError() << std::endl;
        return false;
    } else {
        std::cout << "save station_train success. Table: " << TableName << std::endl;
        return true;
    }
}
